<template>
  <div class="app-container">
    <!-- 仓库和库区选择对话框 -->
    <el-dialog
      title="请选择仓库和库区"
      :visible.sync="warehouseAreaSelectVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form>
        <el-form-item label="仓库" label-width="80px">
          <el-select 
            v-model="selectedWarehouseId" 
            placeholder="请选择仓库" 
            style="width: 100%"
            @change="handleWarehouseChange"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName + ' (' + item.warehouseCode + ')'"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库区" label-width="80px">
          <el-select 
            v-model="selectedAreaId" 
            placeholder="请选择库区" 
            style="width: 100%"
            :disabled="!selectedWarehouseId"
            @change="handleAreaSelection"
          >
            <el-option
              v-for="item in areaList"
              :key="item.areaId"
              :label="item.areaName + ' (' + item.areaCode + ')'"
              :value="item.areaId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 仓库和库区信息 -->
    <el-card shadow="never" class="mb20">
      <div slot="header">
        <span>库位管理 - {{ warehouseInfo.warehouseName }} / {{ areaInfo.areaName }}</span>
        <el-button
          style="float: right; margin-left: 10px; padding: 3px 0"
          type="text"
          icon="el-icon-refresh"
          @click="handleSwitchWarehouse"
        >切换仓库/库区</el-button>
        
      </div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="仓库名称">{{ warehouseInfo.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="仓库编码">{{ warehouseInfo.warehouseCode }}</el-descriptions-item>
        <el-descriptions-item label="仓库状态">
          {{ 
            (statusOptions.find(item => item.dictValue === String(warehouseInfo.warehouseStatus)) || {}).dictLabel 
            || warehouseInfo.warehouseStatus 
          }}
        </el-descriptions-item>
        <el-descriptions-item label="库区名称">{{ areaInfo.areaName }}</el-descriptions-item>
        <el-descriptions-item label="库区编码">{{ areaInfo.areaCode }}</el-descriptions-item>
        <el-descriptions-item label="库区类型">
          {{ 
            (areaTypeOptions.find(item => item.dictValue === String(areaInfo.areaType)) || {}).dictLabel 
            || areaInfo.areaType
          }}
        </el-descriptions-item>
        <el-descriptions-item label="库区状态">
          {{ 
            (statusOptions.find(item => item.dictValue === String(areaInfo.areaStatus)) || {}).dictLabel 
            || areaInfo.areaStatus 
          }}
        </el-descriptions-item>
        <el-descriptions-item label="库位总数">{{ locationCount }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="库位编码" prop="locationCode">
        <el-input
          v-model="queryParams.locationCode"
          placeholder="请输入库位编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位类型" prop="locationType">
        <el-select
          v-model="queryParams.locationType"
          placeholder="请选择库位类型"
          clearable
        >
          <el-option
            v-for="dict in locationTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['wms:location:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:location:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:location:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['wms:location:export']"
        >导出</el-button>
      </el-col>

    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="locationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库位编码" align="center" prop="locationCode" />
      <el-table-column label="库位名称" align="center" prop="locationName" />
      <el-table-column label="库位类型" align="center" prop="locationType">
        <template slot-scope="scope">
          {{ 
            (locationTypeOptions.find(item => item.dictValue === String(scope.row.locationType)) || {}).dictLabel 
            || scope.row.locationType 
          }}
        </template>
      </el-table-column>
      <el-table-column label="库位状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ 
            (statusOptions.find(item => item.dictValue === String(scope.row.locationStatus)) || {}).dictLabel 
            || scope.row.locationStatus 
          }}
        </template>
      </el-table-column>
      <el-table-column label="容量" align="center" prop="capacity">
        <template slot-scope="scope">
          {{ scope.row.maxCapacity || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="已用容量" align="center" prop="usedCapacity">
        <template slot-scope="scope">
          {{ scope.row.usedCapacity || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:location:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:location:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库位编码" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入库位编码" />
        </el-form-item>
        <el-form-item label="库位名称" prop="locationName">
          <el-input v-model="form.locationName" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="库位类型" prop="locationType">
          <el-select v-model="form.locationType" placeholder="请选择库位类型">
            <el-option
              v-for="dict in locationTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库位状态" prop="locationStatus">
          <el-select v-model="form.locationStatus" placeholder="请选择库位状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="form.maxCapacity" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listLocation, 
  getLocation, 
  addLocation, 
  updateLocation, 
  deleteLocation, 
  countLocation 
} from "@/api/wms";
import { getWarehouse, listWarehouse } from "@/api/wms";
import { getArea, listArea } from "@/api/wms";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Location",
  data() {
    return {
      // 仓库和库区选择对话框
      warehouseAreaSelectVisible: false,
      selectedWarehouseId: '',
      selectedAreaId: '',
      warehouseList: [],
      areaList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 库位表格数据
      locationList: [],
      // 仓库信息
      warehouseInfo: {},
      // 库区信息
      areaInfo: {},
      // 库位总数
      locationCount: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 库位类型数据字典
      locationTypeOptions: [],
      // 库区类型数据字典
      areaTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: undefined,
        areaId: undefined,
        locationCode: undefined,
        locationType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        locationCode: [
          { required: true, message: "库位编码不能为空", trigger: "blur" }
        ],
        locationName: [
          { required: true, message: "库位名称不能为空", trigger: "blur" }
        ],
        locationType: [
          { required: true, message: "库位类型不能为空", trigger: "change" }
        ],
        locationStatus: [
          { required: true, message: "库位状态不能为空", trigger: "change" }
        ],
        maxCapacity: [
          { required: true, message: "容量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 先加载字典数据
    this.getDicts().then(() => {
      const warehouseId = this.$route.query.warehouseId;
      const areaId = this.$route.query.areaId;
      if (warehouseId && areaId) {
        this.queryParams.warehouseId = warehouseId;
        this.queryParams.areaId = areaId;
        this.getWarehouseInfo(warehouseId);
        this.getAreaInfo(areaId);
        this.getLocationCount();
        this.getList();
      } else {
        this.showSelectionDialog();
      }
    });
  },
  methods: {
    /** 返回库区列表 */
    handleBack() {
      this.$router.push({ path: "/wms/area", query: { warehouseId: this.queryParams.warehouseId } });
    },

    /** 切换仓库/库区 */
    handleSwitchWarehouse() {
      this.warehouseAreaSelectVisible = true;
      this.selectedWarehouseId = this.queryParams.warehouseId;
      this.selectedAreaId = this.queryParams.areaId;
      this.loadWarehouses();
    },

    // 显示选择对话框
    showSelectionDialog() {
      this.warehouseAreaSelectVisible = true;
      this.loadWarehouses();
    },

    // 加载仓库列表
    loadWarehouses() {
      this.loading = true;
      listWarehouse().then(response => {
        this.warehouseList = response.rows || [];
      }).finally(() => {
        this.loading = false;
      });
    },

    // 仓库选择变化时加载对应库区
    handleWarehouseChange(warehouseId) {
      if (!warehouseId) {
        this.areaList = [];
        this.selectedAreaId = '';
        return;
      }
      
      this.loading = true;
      listArea({ warehouseId }).then(response => {
        this.areaList = response.rows || [];
        // 如果只有一个库区，自动选择
        if (this.areaList.length === 1) {
          this.selectedAreaId = this.areaList[0].areaId;
          this.handleAreaSelection(this.selectedAreaId);
        }
      }).finally(() => {
        this.loading = false;
      });
    },

    // 处理库区选择
    handleAreaSelection(areaId) {
      if (!areaId) return;
      
      const selectedWarehouse = this.warehouseList.find(w => w.warehouseId === this.selectedWarehouseId);
      const selectedArea = this.areaList.find(a => a.areaId === areaId);
      
      this.queryParams.warehouseId = this.selectedWarehouseId;
      this.queryParams.areaId = areaId;
      this.warehouseInfo = selectedWarehouse;
      this.areaInfo = selectedArea;
      this.warehouseAreaSelectVisible = false;
      this.getLocationCount();
      this.getList();
    },

    /** 查询库位列表 */
    getList() {
      this.loading = true;
      listLocation(this.queryParams).then(response => {
        this.locationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 获取仓库信息
    getWarehouseInfo(warehouseId) {
      getWarehouse(warehouseId).then(response => {
        this.warehouseInfo = response.data;
      });
    },

    // 获取库区信息
    getAreaInfo(areaId) {
      getArea(areaId).then(response => {
        this.areaInfo = response.data;
      });
    },

    // 获取库位总数
    getLocationCount() {
      // 检查countLocation是否存在
      if (typeof countLocation === 'function') {
        countLocation({ areaId: this.queryParams.areaId }).then(response => {
          this.locationCount = response.data;
        }).catch(error => {
          console.error('获取库位总数失败:', error);
          this.locationCount = 0;
        });
      } else {
        console.error('countLocation方法未定义');
        this.locationCount = 0;
      }
    },

    // 获取数据字典
    getDicts() {
      return Promise.all([
        // 获取状态字典（用于仓库状态和库区状态）
        getDicts("sys_normal_disable").then(response => {
          this.statusOptions = response.data;
        }).catch(() => {
          // 回退到系统默认状态字典
          return getDicts("sys_normal_disable").then(response => {
            this.statusOptions = response.data;
          });
        }),
        
        // 获取库位类型字典
        getDicts("wms_location_type").then(response => {
          if (response.data && response.data.length > 0) {
            this.locationTypeOptions = response.data;
          } else {
            // 如果字典为空，创建默认库位类型
            return this.createDefaultLocationTypes();
          }
        }).catch(() => {
          // 如果获取失败，创建默认库位类型
          return this.createDefaultLocationTypes();
        }),
        
        // 获取库区类型字典
        getDicts("wms_area_type").then(response => {
          this.areaTypeOptions = response.data;
        }).catch(() => {
          // 回退到通用类型字典
          return getDicts("sys_normal_disable").then(response => {
            this.areaTypeOptions = response.data;
          });
        })
      ]);
    },

    

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        locationId: undefined,
        warehouseId: this.queryParams.warehouseId,
        areaId: this.queryParams.areaId,
        locationCode: undefined,
        locationName: undefined,
        locationType: undefined,
        status: "0",
        capacity: undefined,
        usedCapacity: 0,
        remark: undefined
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.locationId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库位";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const locationId = row.locationId || this.ids;
      getLocation(locationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库位";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.locationId != null) {
            updateLocation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLocation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const locationIds = row.locationId || this.ids;
      this.$modal.confirm('是否确认删除库位编号为"' + locationIds + '"的数据项？').then(function() {
        return deleteLocation(locationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 库存查看按钮操作 */
    handleInventory(row) {
      const locationId = row.locationId;
      this.$router.push({ path: "/wms/inventory", query: { warehouseId: this.queryParams.warehouseId, areaId: this.queryParams.areaId, locationId: locationId } });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.loading = true;
      this.download('wms/location/export', {
        ...this.queryParams
      }, `库位数据_${this.warehouseInfo.warehouseName}_${this.areaInfo.areaName}_${new Date().getTime()}.xlsx`)
      .finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>